package com.share.tools;

import com.itextpdf.text.pdf.BaseFont;
import org.apache.commons.io.IOUtils;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * author:caifan
 * date:2019/5/3
 */
public class PDFUtils {

    public static void main(String[] args) {
//        html2Pdf("D:/test/aa.html", "D:/test/aa.pdf");
        html2Pdf("F:/下载/Spring-Cloud.html", "F:/下载/spring-cloud.pdf");
    }


    public static void html2Pdf(String htmlPath, String pdfPath) {
        FileOutputStream fos = null;
        File file = new File(pdfPath);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);

            ITextRenderer renderer = new ITextRenderer();
            /**
             * 中文字体
             */
            ITextFontResolver resolver = renderer.getFontResolver();
            resolver.addFont("font/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            String content = IOUtils.toString(new FileInputStream(htmlPath));
            content = content.replaceAll("&", "&amp;");
            renderer.setDocumentFromString(content);
            /**
             * 指定图片相对路径目录
             */
            renderer.getSharedContext().setBaseURL("file:D:/test/");
            renderer.layout();
            renderer.createPDF(fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                IOUtils.closeQuietly(fos);
            }
        }
    }
}
